package com.thenie.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thenie.chat.mapper.UserMapper;
import com.thenie.chat.pojo.User;
import com.thenie.chat.service.IUserService;
import com.thenie.chat.util.CookieUtil;
import com.thenie.chat.util.PasswordUtil;
import com.thenie.chat.util.UUIDUtil;
import com.thenie.chat.util.UploadUtil;
import com.thenie.chat.vo.LoginVo;
import com.thenie.chat.vo.RegisterVo;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author thenie
 * @since 2022-05-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 登陆
     * @param vo
     * @param req
     * @param resp
     * @return
     */
    public RespBean doLogin(LoginVo vo, HttpServletRequest req, HttpServletResponse resp){
        String loginName = vo.getUsername();
        String loginPwd = vo.getPassword();

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", loginName));
        if (user!=null){
            String password = user.getPassword();
            String salt = user.getSalt();
            String md5LoginPwd = PasswordUtil.md5(loginPwd, salt, 5);
            //密码正确
            if (md5LoginPwd.equals(password)){
                //生成cookie
                String userTicket = UUIDUtil.uuid();
                //保存到redis中(隐藏user部分信息)
                user.setPassword("");
                user.setSalt("");
                redisTemplate.opsForValue().set("userTicket:"+userTicket, user,1, TimeUnit.DAYS);
                //保存到客户端中
                CookieUtil.setCookie(req,resp,"userTicket",userTicket,86400);

                log.info("------用户登录成功,{}", user);
                return RespBean.success();
            }
        }
        //登陆失败，账号/密码错误
        return RespBean.error(RespBeanEnum.LOGIN_ERROR);
    }

    /**
     * 注册
     * @param registerVo
     * @param req
     * @param resp
     * @return
     */
    @Override
    public RespBean doRegister(RegisterVo registerVo, HttpServletRequest req, HttpServletResponse resp) {
        String username = registerVo.getUsername();
        String password = registerVo.getPassword();
        String email = registerVo.getEmail();
        //对密码加密
        String salt = PasswordUtil.getSalt();
        String dbPwd = PasswordUtil.md5(password, salt, 5);
        //插入到数据库中
        User user = new User();
        user.setUsername(username);
        user.setPassword(dbPwd);
        user.setSalt(salt);
        user.setEmail(email);
        user.setPhoto(UploadUtil.getPhotoDefault());
        user.setRealName(username);
        user.setLocation("火星");
        int ok = userMapper.insert(user);
        if (ok==1){
            //注册成功,取数据库查用户，并保存cookie信息
            user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
            if (user!=null){
                //生成cookie
                String userTicket = UUIDUtil.uuid();
                //保存到redis中(隐藏user部分信息)
                user.setPassword("");
                user.setSalt("");
                redisTemplate.opsForValue().set("userTicket:"+userTicket, user,1, TimeUnit.DAYS);
                //保存到客户端中
                CookieUtil.setCookie(req,resp,"userTicket",userTicket,86400);

                log.info("------用户注册成功{}",user);
                return RespBean.success("注册成功");
            }
        }

        return RespBean.error(RespBeanEnum.REGISTER_ERROR);
    }

    /**
     * 判断邮箱是否存在
     * @param email
     * @return
     */
    @Override
    public boolean checkEmailIsExist(String email) {
        User user = userMapper.selectOne(new QueryWrapper<User>().select("email").eq("email", email));
        if (StringUtils.isEmpty(user)){
            //邮箱不存在
            return false;
        }
        return true;
    }

    /**
     * 判断用户名是否存在
     * @param username
     * @return
     */
    @Override
    public boolean checkUsernameIsExist(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().select("username").eq("username", username));
        if (StringUtils.isEmpty(user)){
            //用户名不存在
            return false;
        }
        return true;
    }

    /**
     * 根据用户ID获取用户
     * @param id
     * @return
     */
    public User getUserById(Long id){
        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public User getUserByUsername(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        user.setSalt("");
        user.setPassword("");
        user.setCreateDate(null);
        return user;
    }

    /**
     * 根据邮箱获取用户
     * @param email
     * @return
     */
    @Override
    public User getUserByEmail(String email) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));
        user.setSalt("");
        user.setPassword("");
        user.setCreateDate(null);
        return user;
    }

    /**
     * 根据userTicket获取user
     * @param ticket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserByCookie(String ticket, HttpServletRequest request, HttpServletResponse response) {
        User user =null;
        if (StringUtils.isEmpty(ticket)){
            return null;
        }

        user = (User)redisTemplate.opsForValue().get("userTicket:" + ticket);

        if (null != user){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }

        return user;
    }

    /**
     * 删除登陆状态，userTicket
     * @param ticket
     * @return
     */
    @Override
    public Boolean deleteUserTicketFormMe(String ticket) {
        if (!StringUtils.isEmpty(ticket)){
            return redisTemplate.delete("userTicket:"+ticket);
        }

        return false;
    }

}
